package han.fetch;

import com.han.http.client.paramter.RequestHeader;
import han.entity.InvestCompanyIdEntity;
import han.exception.MuchRequestException;
import han.exception.UnLoginException;
import han.parser.InvestOrganizationIdParser;
import han.proof.Cookie;
import han.sql.InsertThread;

import java.util.List;
import java.util.Random;
import java.util.Set;

import static com.han.http.util.Print.printlnErr;
import static com.han.http.util.Print.printlnInfo;

/**
 * @author: Han
 * @date: 2018/8/9 11:00
 * @dscription: 抓取投资机构id
 */
public class InvestOrganizationIdThread implements Runnable {
    private final Object krLock;
    private List<Integer> pageList;
    private Cookie cookie;
    private InsertThread insertThread;

    InvestOrganizationIdThread(List<Integer> pageList, Cookie cookie, InsertThread insertThread, Object krLock) {
        this.pageList = pageList;
        this.cookie = cookie;
        this.insertThread = insertThread;
        this.krLock = krLock;
    }

    @Override
    public void run() {
        getInvestOrgId();
        insertThread.executeInsertInvestOrgIdAtOnce();
    }

    private void getInvestOrgId() {
        Random random = new Random();
        int interval;
        Fetcher fetcher = new Fetcher();
        String rowUrl = "https://rong.36kr.com/n/api/org/list?page=";
        int generalTimeout = 1000 * 10;
        RequestHeader[] requestHeaders = {
                new RequestHeader("Accept", "application/json, text/plain, */*"),
                new RequestHeader("Accept-Encoding", "gzip, deflate, br"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("Host", "rong.36kr.com"),
                new RequestHeader("Referer", "https://rong.36kr.com/org/list&?page=5"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.23 Safari/537.36"),
                new RequestHeader("X-Tingyun-Id", "Dio1ZtdC5G4;r=94814518"),
        };
        for (int page : pageList) {
            interval = random.nextInt(1000 * 3) + 1000 * 7;
            String usedUrl = rowUrl + page;
            try {
                String data;
                synchronized (krLock) {
                    //同步锁
                    data = fetcher.getInfoByGet(usedUrl, requestHeaders, generalTimeout,
                            generalTimeout, null);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //如果账号被暂时封禁,抛出异常
                if (data.contains("您请求的过于频繁，请稍后再试")) {
                    throw new MuchRequestException();
                }
                //如果cookie失效,可能登录期限已过或者账号被永久封禁
                if (data.contains("用户未登录")) {
                    throw new UnLoginException();
                }
                Set<InvestCompanyIdEntity> entitySet = InvestOrganizationIdParser.getId(data);
                insertThread.insertInsertOrgId(entitySet);
                printlnInfo(cookie.getLoginName() + ":第" + page + "页抓取成功,"
                        + pageList.get(0) + "->" + pageList.get(pageList.size() - 1));
            } catch (MuchRequestException e) {
                printlnErr(cookie.getLoginName() + ":Cookie被封");
                cookie.setStatus(1);
            } catch (UnLoginException e) {
                printlnInfo(cookie.getLoginName() + ":可能被永久封禁了");
                cookie.setStatus(2);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    Thread.sleep(interval);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
